﻿using System;
using System.Collections.Generic;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Windows.Forms;
using iSun.ServerFile;
using System.Configuration;
using System.IO;
using iSun.Entity;
using System.Data.Services.Client;
using log4net;
using System.Management;


namespace iSun.App
{
    public static class DataAction
    {
        #region 同步服务器数据
        public static IList<iSun.App.DataSerivce.vendor> GetVendorList()
        {
            iSun.App.DataSerivce.cha cha = new iSun.App.DataSerivce.cha();
            iSun.App.DataSerivce.jsEntities jsEntity = new iSun.App.DataSerivce.jsEntities(new Uri("http://202.70.26.133/jsdatadataservice.svc"));
            QueryOperationResponse<iSun.App.DataSerivce.vendor> response = jsEntity.vendor.Execute() as QueryOperationResponse<iSun.App.DataSerivce.vendor>;
            IList<iSun.App.DataSerivce.vendor> list = new List<iSun.App.DataSerivce.vendor>();
            foreach (var vendor in response)
            {
                list.Add(vendor);    
            }
            return list;
        }

        public static void SynSerivceDataToClient()
        {
            iSun.App.DataSerivce.cha cha = new iSun.App.DataSerivce.cha();
            iSun.App.DataSerivce.jsEntities jsEntity = new iSun.App.DataSerivce.jsEntities(new Uri("http://202.70.26.133/jsdatadataservice.svc"));

            // var query = jsEntity.CreateQuery<iSun.App.DataSerivce.jew>("jew");
            // DataServiceCollection<iSun.App.DataSerivce.jew> query = new DataServiceCollection<iSun.App.DataSerivce.jew>();

            DataServiceQueryContinuation<iSun.App.DataSerivce.jew> token = null;
            int pageCount = 0;

            QueryOperationResponse<iSun.App.DataSerivce.jew> response = jsEntity.jew.Execute() as QueryOperationResponse<iSun.App.DataSerivce.jew>;
            try
            {
                do
                {
                    // Write the page number.
                    // Console.WriteLine("Page {0}:", pageCount++);
                    pageCount++;

                    // If nextLink is not null, then there is a new page to load.
                    if (token != null)
                    {
                        // Load the new page from the next link URI.
                        response = jsEntity.Execute<iSun.App.DataSerivce.jew>(token)
                            as QueryOperationResponse<iSun.App.DataSerivce.jew>;
                    }

                   // log4net.LogManager.GetLogger("__test__").Info("-----" + System.DateTime.Now.ToLongTimeString() + "----------");
                    foreach (var entity in response)
                    {
                        iSun.Entity.ProductPhotoEnitty p = new ProductPhotoEnitty();
                        ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(p);
                        var _entity = bll.GetEntityByCondition<iSun.Entity.ProductPhotoEnitty>(string.Format("Vendor_id={0} and SN='{1}'", entity.ven_id, entity.code));
                        if (_entity != null)
                        {
                            continue;
                        }
                        else
                        {
                            p.SN = entity.code;
                            p.ProductName = entity.code;
                            p.Description = entity.name;
                            p.AddTime = entity.createDate;// System.DateTime.Now;
                            p.AddUser = Guid.Empty;
                            p.isActive = entity.isActive;
                            p.Vendor_id = entity.ven_id;

                            System.Console.WriteLine();
                            System.Console.Write(ZX.Common.Globals.ObjectToJSON(p));
                            if (_entity == null)
                            {
                                try
                                {
                                    bll.Insert();
                                }
                                catch (Exception e) { }
                            }
                            else
                            {
                                bll.Update();
                            }
                        }
                    }
                }
                while ((token = response.GetContinuation()) != null);
            }
            catch (DataServiceQueryException ex)
            {
                throw new ApplicationException(
                    "An error occurred during query execution.", ex);
            }
        }
        #endregion

        #region 更新配罩文件
        /// <summary>
        /// 更新配置的Key/Value
        /// </summary>
        /// <param name="newKey"></param>
        /// <param name="newValue"></param>
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            bool isModified = true;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == newKey) { isModified = true; }
            }       
            //Open App.Config of executable     
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // You need to remove the old settings object before you can replace it   
            if (isModified) { config.AppSettings.Settings.Remove(newKey); }
            // Add an Application Setting.  
            config.AppSettings.Settings.Remove(newKey);
            config.AppSettings.Settings.Add(newKey, newValue);
            // Save the changes in App.config file.   
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of a changed section.     
            ConfigurationManager.RefreshSection("appSettings");
        }


        public static void Rename(string oldName, string newName)
        {
            
        }

        #endregion

        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="SN"></param>
        /// <returns></returns>
        public static FileInfo[] GetFile(string SN)
        {
            string __path = ConfigurationManager.AppSettings["defualtSourceFilePath"];
            DirectoryInfo dir = new DirectoryInfo(__path);
            string __newPath = ConfigurationManager.AppSettings["filePath"];
            FileInfo[] __files = dir.GetFiles();
            return __files;
        }


        #region 文件移动
        public static FileInfo[] MoveFile(out int flag, string SN)
        {
            flag = 0;
            string vendor_id = iSun.App.UserInfo.CurrentVendor_id;
            string __path = ConfigurationManager.AppSettings["defualtSourceFilePath"];
            DirectoryInfo dir = new DirectoryInfo(__path);
            string ___newPath = ConfigurationManager.AppSettings["filePath"];
            string ___backPath =  ConfigurationManager.AppSettings["filePath"];
            FileInfo[] __files = dir.GetFiles();
            string __newPath = "";
            foreach (FileInfo file in __files)
            {
                if (SN.Length > 36)
                {
                    __newPath = "";
                    string[] _strArr = SN.Split('_');
                    string __SN = _strArr[1];
                    string __type = _strArr[2];
                    //string __newPath = ConfigurationManager.AppSettings["filePath"];
                    __newPath = ___newPath + __SN + "_" + vendor_id + "\\";//上传目录加上供应商信息
                    string __ttype = "";
                    switch (__type)
                    {
                        case "0":
                            __newPath = __newPath + "images\\";
                            __ttype = "P";
                            break;
                        case "1":
                            __newPath = __newPath + "thumb\\";
                            __ttype = "T";
                            break;
                        case "2":
                            __newPath = __newPath + "vedio\\";
                            __ttype = "V";
                            break;
                        default:
                            __newPath = __newPath + "images\\";
                            __ttype = "P";
                            break;
                    }
                    if (!Directory.Exists(__newPath))
                    {
                        Directory.CreateDirectory(__newPath);
                    }

                    #region 备份数据到本地
                    if (!Directory.Exists(___backPath + __newPath.Replace(___newPath, "")))
                    {
                        Directory.CreateDirectory(___backPath + __newPath.Replace(___newPath, ""));
                    }
                    file.CopyTo(___backPath + __newPath.Replace(___newPath, "") + __SN + "_" + __ttype + "_" + file.Name,true);
                    #endregion

                    file.MoveTo(__newPath + __SN + "_" + __ttype + "_" + file.Name);
                    flag = 1;
                }
            }
            return (new DirectoryInfo(__newPath)).GetFiles();
        }
        public static void MoveFile(string SN, out int flag)
        {
            string vendor_id = iSun.App.UserInfo.CurrentVendor_id;
            flag = 0;
            string __path = ConfigurationManager.AppSettings["defualtSourceFilePath"];
            string ___newPath = ConfigurationManager.AppSettings["filePath"];
            string ___backPath = ConfigurationManager.AppSettings["backPath"];
            DirectoryInfo dir = new DirectoryInfo(__path);
            FileInfo[] __files = dir.GetFiles();
            foreach (FileInfo file in __files)
            {
                if (SN.Length > 36)
                {
                    string[] _strArr = SN.Split('_');
                    string __SN = _strArr[1];
                    string __type = _strArr[2];
                    string __newPath = ConfigurationManager.AppSettings["filePath"];
                    __newPath = __newPath + __SN + "_"+vendor_id+"\\";
                    //所有的目录加上供应商信息
                    string __ttype = "";
                    switch (__type)
                    {
                        case "0":
                            __newPath = __newPath + "images\\";
                            __ttype = "P";
                            break;
                        case "1":
                            __newPath = __newPath + "thumb\\";
                            __ttype = "T";
                            break;
                        case "2":
                            __newPath = __newPath + "vedio\\";
                            __ttype = "V";
                            break;
                        default:
                            __newPath = __newPath + "images\\";
                            __ttype = "P";
                            break;
                    }


                    if (!Directory.Exists(__newPath))
                    {
                        Directory.CreateDirectory(__newPath);
                    }

                    #region 备份数据到本地
                    if (!Directory.Exists(___backPath + __newPath.Replace(___newPath, "")))
                    {
                        Directory.CreateDirectory(___backPath + __newPath.Replace(___newPath, ""));
                    }
                    file.CopyTo(___backPath + __newPath.Replace(___newPath, "") + __SN + "_" + __ttype + "_" + file.Name, true);
                    #endregion
                    if (System.IO.File.Exists(__newPath + __SN + "_" + __ttype + "_" + file.Name))
                    {
                        System.IO.File.Delete(__newPath + __SN + "_" + __ttype + "_" + file.Name);
                    }
                    file.MoveTo(__newPath + __SN + "_" + __ttype + "_" + file.Name);
                    flag = 1;
                }
            }

            string path = ConfigurationManager.AppSettings["filePath"];// : ConfigurationManager.AppSettings["filePath1"];
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            uFile(path, channel, 0);
        }
        #endregion

        /// <summary>
        /// 生成相关目录
        /// </summary>
        /// <param name="SN"></param>
        public static void CreateProductDir(string SN)
        {
            
            string __path = ConfigurationManager.AppSettings["filePath"];

            if (!Directory.Exists(__path + SN))
            {
                Directory.CreateDirectory(__path + SN);
                Directory.CreateDirectory(__path + SN + "\\images");
                Directory.CreateDirectory(__path + SN + "\\thumb");
                Directory.CreateDirectory(__path + SN + "\\vedio");
            }
        }


        #region 下载文件


        public static void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            float percent = 0;
            try
            {
                label1.Text = filename;
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);
                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;

                    //label1.Text = "当前补丁下载进度" + percent.ToString() + "%";
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception ex)
            {
                ZX.Log.XTrace.WriteLine("-------------------------------begin---------------------------------");
                ZX.Log.XTrace.WriteLine(System.DateTime.Now.ToString());
                ZX.Log.XTrace.WriteLine(ex.Message);
                ZX.Log.XTrace.WriteLine("-------------------------------end-----------------------------------");
            }
        }

   

        public static IList<iSun.Entity.ProductPhotoEnitty> GetProduct(string productID)
        {
            WebClient MyWebClient = new WebClient();
            MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。
            string url = ConfigurationManager.AppSettings["SeverURL"] + string.Format("/Extend/AjaxData/DataTableJsonList.aspx?type=1&entity=Gs_Product&condition=id= '{0}'", productID);
            Byte[] pageData = MyWebClient.DownloadData(url);
            string data = System.Text.Encoding.UTF8.GetString(pageData);
            if (data == "[]")
            {
                ZX.Log.XTrace.WriteLine("----------------------------上传---begin---------------------------------");
                ZX.Log.XTrace.WriteLine(System.DateTime.Now.ToString());
                ZX.Log.XTrace.WriteLine(url);
                ZX.Log.XTrace.WriteLine(data);
                ZX.Log.XTrace.WriteLine("-------------------------------end-----------------------------------");
                return null;
            }
            IList<iSun.Entity.ProductPhotoEnitty> list = new List<iSun.Entity.ProductPhotoEnitty>();
            var entity = ZX.Common.Globals.JSonToObject<iSun.Entity.ProductPhotoEnitty>(data.Replace("[[", "").Replace("]]", ""));
            if (entity != null)
            {
                list.Add(entity);
            }
            return list;
        }

        /// <summary>
        /// 获取要下载的产品列表
        /// </summary>
        /// <param name="productID"></param>
        /// <param name="stepN"></param>
        /// <returns></returns>
        public static IList<iSun.Entity.ProductImage> GetProductImages(string productID, int stepN)
        {
            WebClient MyWebClient = new WebClient();
            MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于对向Internet资源的请求进行身份验证的网络凭据。
            string url = ConfigurationManager.AppSettings["SeverURL"] + string.Format("/Extend/AjaxData/DataTableJsonList.aspx?type=1&entity=Gs_ProductImage&condition=ProductID= '{0}' and stepN={1}", productID,stepN);
            Byte[] pageData = MyWebClient.DownloadData(url);
            string data = System.Text.Encoding.UTF8.GetString(pageData);
            if (data == "[]")
            {
                return null;
            }
            return ZX.Common.Globals.JSonToObject<IList<iSun.Entity.ProductImage>>(data.Replace("[[", "[").Replace("]]", "]"));
       
        }

        public static void DownLandFile(string SN,string VendorID,bool isSourceFile,System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1, System.Windows.Forms.Label label2)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            BasicHttpBinding binding2 = new BasicHttpBinding();
            binding2.TransferMode = TransferMode.Streamed;
            int stepN = isSourceFile ? 0 : 1;
            IList<iSun.Entity.ProductImage> _filelist = GetProductImages(SN,stepN);
            if (_filelist == null)
            {
                label2.Text = "没有文件可供下载";
                return;
            }
            foreach (iSun.Entity.ProductImage entity   in _filelist)
            {
                string  __files = entity.FilePath;
                string __path = "";
                if (__files.ToLower().Contains("\\upload\\photo"))
                {
                    __path = isSourceFile ? ConfigurationManager.AppSettings["filePath1"] : ConfigurationManager.AppSettings["downModifiedFile"];
                }
                else
                {
                    __path = (isSourceFile ? ConfigurationManager.AppSettings["filePath1"] : ConfigurationManager.AppSettings["downModifiedFile"])
                + (SN == "root" ? "" : SN);
                }
                string __file = __files.Replace("\\upload\\photo1\\", "").Replace("\\upload\\photo\\", "");
                
                // 处理异常情况
                string _SN = __file.Split('\\')[0];
                if (_SN.EndsWith("_"))
                {
                    __file=__file.Remove(0,_SN.Length);
                    _SN = _SN + VendorID;
                    __file = _SN + __file;
                    
                }
                if(_SN.IndexOf('_')<0)
                {
                    __file = __file.Remove(0, _SN.Length);
                    _SN=_SN+"_"+VendorID;
                    __file = _SN + __file;
                }

                string filePath = __path + __file;
                if (isSourceFile)
                {
                    filePath = ZX.Common.FileHelper.GetFileDir(filePath) + "\\Source\\" + ZX.Common.FileHelper.GetFileNameNoPath(filePath);
                }

                string[] ___path = filePath.Split('\\');
                string ___dir = ZX.Common.FileHelper.GetFileDir(filePath);
                if (!Directory.Exists(___dir))
                {
                    Directory.CreateDirectory(___dir);
                }
                if (isSourceFile)
                {
                    if (!Directory.Exists(ZX.Common.FileHelper.GetFileDir(filePath) + "\\Modifing\\"))
                    {
                        Directory.CreateDirectory(ZX.Common.FileHelper.GetFileDir(__path + __file) + "\\Modifing");
                    }
                }
                label2.Text = __file;
                string url = "";
                if (__files.Contains("\\upload\\photo"))
                {
                    url = ConfigurationManager.AppSettings["SeverURL"] + entity.FilePath.Replace('\\', '/');
                }
                else
                {
                    url = ConfigurationManager.AppSettings["SeverURL"] + "upload/photo/" + (SN == "root" ? "" : SN) + __files.Replace('\\', '/');
                }
                DownloadFile(url, filePath, prog, label1);
            }
        }


        public static void DownLandFile(string SN, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1, System.Windows.Forms.Label label2, bool IsSourceFile)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            BasicHttpBinding binding2 = new BasicHttpBinding();
            binding2.TransferMode = TransferMode.Streamed;

            IList<string> _filelist = channel.GetSNFiles(SN, false);
            if (_filelist == null)
            {
                return;
            }
            foreach (string __files in _filelist)
            {
                string __path = ConfigurationManager.AppSettings["filePath1"] + (SN == "root" ? "" : SN);
                string filePath = __path + __files.Replace("\\upload\\photo1\\"+SN,"");
                if (!IsSourceFile)
                {
                    filePath = ZX.Common.FileHelper.GetFileDir(filePath) + "\\Modified\\" + ZX.Common.FileHelper.GetFileNameNoPath(filePath);
                }
                string[] ___path = filePath.Split('\\');
                string ___dir = filePath.Replace(___path[___path.Length - 1], "");
                if (!Directory.Exists(___dir))
                {
                    Directory.CreateDirectory(___dir);
                }
                label2.Text = __files;
                string url = ConfigurationManager.AppSettings["SeverURL"] + "upload/photo1/" + (SN == "root" ? "" : SN) + __files.Replace('\\', '/');
                DownloadFile(url, filePath, prog, label1);
            }
        }


        public static void DownLandFile()
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            BasicHttpBinding binding2 = new BasicHttpBinding();
            binding2.TransferMode = TransferMode.Streamed;

            IList<string> _filelist = channel.GetFiles();
            foreach (string __files in _filelist)
            {
                iSun.DownloadRequest request = new iSun.DownloadRequest();
                request.FileName = __files;
                iSun.FileUploadMessage __Data = channel.GetProduct(request);
                string __path = ConfigurationManager.AppSettings["filePath"];
                string filePath = __path + __files;

                string[] ___path = filePath.Split('\\');
                string ___dir = filePath.Replace(___path[___path.Length - 1], "");
                if (!Directory.Exists(___dir))
                {
                    Directory.CreateDirectory(___dir);
                }

                FileStream targetStream = null;
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    //read from the input stream in 4K chunks
                    //and save to output stream
                    const int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = __Data.FileData.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    __Data.FileData.Close();
                    //stream(entity);
                }
            }
        }

        #endregion

        public static void InitFiles(int stepN)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            BasicHttpBinding binding2 = new BasicHttpBinding();
            binding2.TransferMode = TransferMode.Streamed;
            string path = stepN == 0 ? ConfigurationManager.AppSettings["step0_path"] : ConfigurationManager.AppSettings["step1_path"];
            if (stepN == 0)
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                IList<ProductPhotoEnitty> list = new List<ProductPhotoEnitty>();
                foreach (DirectoryInfo _dir in dir.GetDirectories())
                {
                    if (stepN == 1 && _dir.Name.ToLower().Contains("\\source"))
                    {
                        continue;
                    }
                    if (stepN == 1 && _dir.Name.ToLower().Contains("\\modified"))
                    {
                        continue;
                    }
                    ProductPhotoEnitty pEntity = new ProductPhotoEnitty();
                    pEntity.SN = _dir.Name;
                    pEntity.ProductName = _dir.Name;
                    pEntity.ID = new Guid();
                    list.Add(pEntity);
                }
                channel.UploadProduct(ZX.Common.Globals.ListToJson<ProductPhotoEnitty>(list));
            }
            using (channel as IDisposable)
            {
                uFile(path, channel, stepN);
            }
        }
        public static void SetFlag(string SN, string Flag)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            channel.SetFlag(SN, Flag);
            MessageBox.Show("设置成功");
        }
        public static void DeleteImages(string imagesPath)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            channel.DeleteProuctImages(imagesPath);
        }


        #region 更新文件到服务器
        public static void UploadFile(int stepN)
        {

            string path = ConfigurationManager.AppSettings["step" + stepN + "_path"];// : ConfigurationManager.AppSettings["filePath1"];
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            uFile(path, channel, stepN);
        }


        /// <summary>
        /// 上传源图片到服务器
        /// </summary>
        /// <param name="stepN">步骤（0 或 1）</param>
        public static void UploadSourceFile(int stepN)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            BasicHttpBinding binding2 = new BasicHttpBinding();
            binding2.TransferMode = TransferMode.Streamed;
            string path = stepN == 0 ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
            if (stepN == 0)
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                IList<ProductPhotoEnitty> list = new List<ProductPhotoEnitty>();
                foreach (DirectoryInfo _dir in dir.GetDirectories())
                {
                    if (stepN == 1 && _dir.Name.ToLower().Contains("\\source"))
                    {
                        continue;
                    }
                    ProductPhotoEnitty pEntity = new ProductPhotoEnitty();
                    pEntity.SN = _dir.Name;
                    pEntity.ProductName = _dir.Name;
                    pEntity.ID = new Guid();
                    list.Add(pEntity);
                }
                //  channel.UploadProduct(ZX.Common.Globals.ListToJson<ProductPhotoEnitty>(list));
            }
            using (channel as IDisposable)
            {
                uFile(path, channel, stepN);
            }
        }


        /// <summary>
        /// 更新文件到服务器
        /// </summary>
        /// <param name="path">文件</param>
        /// <param name="channel"></param>
        /// <param name="stepN"></param>
        static void uFile(string path, iSun.IUpLoadService channel, int stepN)
        {
            DirectoryInfo dir = new DirectoryInfo(path);

            FileInfo[] allFile = dir.GetFiles();
            foreach (FileInfo fi in allFile)
            {
                if (fi.Name.ToLower().StartsWith("uploaded_"))
                {
                    continue;
                }
                if (stepN == 1 && ZX.Common.FileHelper.GetFileDir(fi.FullName).ToLower().Contains("\\source"))
                {
                    continue;
                }
                if (stepN == 1 && ZX.Common.FileHelper.GetFileDir(fi.FullName).ToLower().Contains("\\modified"))
                {
                    continue;
                }
                string _path = stepN == 0 ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
                ProductImage entity = new ProductImage();

                entity.fileName = fi.Name;
                entity.FilePath = fi.FullName.Replace(_path, "").Replace(fi.Name, "");
                entity.SN = entity.FilePath.Split('\\')[0];
                entity.ProductID = UserInfo.CurrentProductID;
                entity.DirectoryName = fi.DirectoryName.Replace(_path, "");

                entity.StepN = stepN;

                entity.SourceFileName = fi.Name;
                entity.FileType = fi.Extension;

                entity.ImageType = "0";
                entity.ImageType = entity.FilePath.Contains("\\thumb\\") ? "1" : entity.ImageType;
                entity.ImageType = entity.FilePath.Contains("\\vedio\\") ? "2" : entity.ImageType;
                //entity.ImageType = 
                if (fi.Extension.ToLower().IndexOf("jpg") > -1)
                {
                    Fotofly.JpgPhoto jpgPhotoOne = ZX.Common.IPTC.ReadImageInfo.Load(fi.FullName);
                    entity.Summary = jpgPhotoOne.Metadata.Comment;
                    entity.CreationSoftware = jpgPhotoOne.Metadata.CreationSoftware;
                    entity.CameraManufacturer = jpgPhotoOne.Metadata.CameraManufacturer;
                    entity.CameraModel = jpgPhotoOne.Metadata.CameraModel;
                    entity.Copyright = jpgPhotoOne.Metadata.Copyright;
                    entity.HeigthPix = jpgPhotoOne.Metadata.ImageHeight;
                    entity.WidthPix = jpgPhotoOne.Metadata.ImageWidth;
                }


                iSun.FileUploadMessage file = new iSun.FileUploadMessage();
                //entity.FileSize = (int) fi.Length;
                string json = ZX.Common.Globals.ObjectToJSON(entity);
                file.SavePath = json;
                file.FileName = fi.Name;// "IMG_0467.jpg";
                file.FileData = new FileStream(fi.FullName, FileMode.Open);

                //UpLoadService.FileUploadMessage request = new UpLoadService.FileUploadMessage();
                //request.FileName = FileUpload1.FileName;
                //request.SavePath = "ooooooo";
                //request.FileData = FileUpload1.FileContent;
                //UpLoadService.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
                channel.UploadFile(file);
                //channel.UploadFile(file);
                file.FileData.Close();
                //fi.Decrypt
                try
                {
                    fi.MoveTo(fi.FullName.Replace(fi.Name, "") + "Uploaded_" + fi.Name);
                }
                catch (Exception e)
                {
                }
            }
            foreach (DirectoryInfo _dir in dir.GetDirectories())
            {
                uFile(_dir.FullName, channel, stepN);
            }
        }
        #endregion
    }



    public static class DataManager
    {
        #region 私有变量
        static IFilesService channel;
        static string baseAddress = "http://localhost:12251/";
        #endregion

        #region 属性
        public static string BaseAddress
        {
            get { return baseAddress; }
            set
            {
                channel = null;
                baseAddress = value;
            }
        }

        public static IFilesService Channel
        {
            get
            {
                if (channel == null)
                {
                    WebHttpBinding binding = new WebHttpBinding() { TransferMode = TransferMode.Streamed, MaxReceivedMessageSize = 2147483647 };
                    binding.Security.Mode = WebHttpSecurityMode.None;
                    EndpointAddress address = new EndpointAddress(new Uri(baseAddress));
                    var channelFactory = new ChannelFactory<IFilesService>(binding, address);
                    channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior() { DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, FaultExceptionEnabled = true });
                    channel = channelFactory.CreateChannel();
                }
                return channel;
            }
        }
        #endregion

        public static void SetControlText(Control col, string text)
        {
            if (col.InvokeRequired && col.IsHandleCreated)
                col.BeginInvoke(new Action<Control, string>(SetControlText), col, text);
            else
                col.Text = text;
        }
    }



    public static class SystemInfo
    {
        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        public static string Get_UserIP()
        {
            string ip = "";
            string strHostName = Dns.GetHostName(); //得到本机的主机名
            IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP
            if (ipEntry.AddressList.Length > 0)
            {
                ip = ipEntry.AddressList[0].ToString();
            }
            return ip;
            //string userip = "";
            //string name = Dns.GetHostName();
            //IPAddress[] ips = Dns.GetHostAddresses(name);
            //foreach (IPAddress ip in ips)
            //    userip += ip.ToString() + "|";//所有IP
            //return userip;
        }
        /// <summary>
        /// 获取主机域名
        /// </summary>
        /// <returns></returns>
        public static string Get_HostName()
        {
            return Dns.GetHostName();
        }
        ///// <summary>
        ///// 获取CPU编号
        ///// </summary>
        ///// <returns>返回一个字符串类型</returns>
        //public static string Get_CPUID()
        //{
        //    try
        //    {
        //        //需要在解决方案中引用System.Management.DLL文件
        //        ManagementClass mc = new ManagementClass("Win32_Processor");
        //        ManagementObjectCollection moc = mc.GetInstances();
        //        string strCpuID = null;
        //        foreach (ManagementObject mo in moc)
        //        {
        //            strCpuID = mo.Properties["ProcessorId"].Value.ToString();
        //            break;
        //        }
        //        return strCpuID;
        //    }
        //    catch
        //    {
        //        return "";
        //    }
        //}
        ///// <summary>
        ///// 获取第一分区硬盘编号
        ///// </summary>
        ///// <returns>返回一个字符串类型</returns>
        //public static string GetHardDiskID()
        //{
        //    try
        //    {
        //        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
        //        string strHardDiskID = null;
        //        foreach (ManagementObject mo in searcher.Get())
        //        {
        //            strHardDiskID = mo["SerialNumber"].ToString().Trim();
        //            break;
        //        }
        //        return strHardDiskID;
        //    }
        //    catch
        //    {
        //        return "";
        //    }
        //}
        ///// <summary>
        ///// 获取网卡的MAC地址
        ///// </summary>
        ///// <returns>返回一个string</returns>
        //public static string GetNetCardMAC()
        //{
        //    try
        //    {
        //        string stringMAC = "";
        //        ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
        //        ManagementObjectCollection MOC = MC.GetInstances();
        //        foreach (ManagementObject MO in MOC)
        //        {
        //            if ((bool)MO["IPEnabled"] == true)
        //            {
        //                stringMAC += MO["MACAddress"].ToString();
        //            }
        //        }
        //        return stringMAC;
        //    }
        //    catch
        //    {
        //        return "";
        //    }
        //}
        ///// <summary>
        ///// 获取当前网卡IP地址
        ///// </summary>
        ///// <returns></returns>
        //public static string GetNetCardIP()
        //{
        //    try
        //    {
        //        string stringIP = "";
        //        ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
        //        ManagementObjectCollection MOC = MC.GetInstances();
        //        foreach (ManagementObject MO in MOC)
        //        {
        //            if ((bool)MO["IPEnabled"] == true)
        //            {
        //                string[] IPAddresses = (string[])MO["IPAddress"];
        //                if (IPAddresses.Length > 0)
        //                {
        //                    stringIP = IPAddresses[0].ToString();
        //                }
        //            }
        //        }
        //        return stringIP;
        //    }
        //    catch
        //    {
        //        return "";
        //    }
        //}
        //public static string GetOutIP()
        //{
        //    string strUrl = "http://www.ip138.com/ip2city.asp"; //获得IP的网址了 
        //    Uri uri = new Uri(strUrl);
        //    System.Net.WebRequest wr = System.Net.WebRequest.Create(uri);
        //    System.IO.Stream s = wr.GetResponse().GetResponseStream();
        //    System.IO.StreamReader sr = new System.IO.StreamReader(s, Encoding.Default);
        //    string all = sr.ReadToEnd(); //读取网站的数据           
        //    int i = all.IndexOf("[") + 1;
        //    string tempip = all.Substring(i, 15);
        //    string ip = tempip.Replace("]", "").Replace(" ", "");//找出i
        //    //也可用
        //    //new Regex(@"ClientIP: \[([\d.]+?)\]").Match(new System.Net.WebClient().DownloadString("http://www.skyiv.com/info/")).Groups[1].Value;
        //    return ip;
        //}
    }
}
